package com.hanbang.chu_xing_gao_zhao.view_information;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;

import com.hanbang.chu_xing_gao_zhao.application.HttpInterfaces;
import com.hanbang.chu_xing_gao_zhao.base.BaseActivity;
import com.hanbang.chu_xing_gao_zhao.entity.DynamicBodyData;
import com.hanbang.chu_xing_gao_zhao.entity.InformationDetailsData;
import com.hanbang.chu_xing_gao_zhao.myview.ListViewForScrollView;
import com.hanbang.chu_xing_gao_zhao.utils.JsonHelper;
import com.hanbang.chu_xing_gao_zhao.utils.MyLog;
import com.hanbang.chu_xing_gao_zhao.utils.MyRequestCallBack;
import com.hanbang.chu_xing_gao_zhao.utils.MySharedPreferences;
import com.hanbang.chu_xing_gao_zhao.utils.MyToast;
import com.hanbang.chu_xing_gao_zhao.utils.SharedUtil;
import com.hanbang.chu_xing_gao_zhao.utils.StringUtils_2;
import com.hanbang.chu_xing_gao_zhao.utils.SystemTools;
import com.hanbang.chu_xing_gao_zhao.utils.UiUtils;
import com.hanbang.chu_xing_gao_zhao.view_public.DynamicCommentActivity;
import com.hanbang.chu_xing_gao_zhao.view_dynamic.DynamicSearchActivity;
import com.hanbang.cxgz_2.R;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

public class InformationDetailsActivity extends BaseActivity {
    private TextView title;
    /**
     * 标题图片
     */
    private ImageView icon;
    private WebView content;

    private ImageView search;
    private LinearLayout share;
    private LinearLayout comment;
    private LinearLayout feedLike;
    private InformationDetailsData data;

    /**
     * 信息id
     */
    private int positionId;

    private String userTlephone;
    private String userPassword;
    /**
     * 好友回复 收藏
     */
    private CheckBox collect;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.information_details);
        initView();
        setOnClickListener();

    }

    /**
     * 状态
     *
     * @author yang
     *         INIT：初始调用
     *         SHARE：分享
     *         COMMENT：评价
     *         FEEDLIKE：赞
     *         COLLECT：收藏
     *         COLLECT_cancel：取消收藏
     *         COLLECT_whether：是否收藏
     */
    public enum Status {
        INIT, SHARE, COMMENT, FEEDLIKE, COLLECT, COLLECT_cancel, COLLECT_whether;
    }

    /**
     * 初始化view
     */
    private void initView() {
        userTlephone = MySharedPreferences.getSharedPreferencesKeyAndValue(InformationDetailsActivity.this, MySharedPreferences.USER_DATA, "tlephone");
        userPassword = MySharedPreferences.getSharedPreferencesKeyAndValue(InformationDetailsActivity.this, MySharedPreferences.USER_DATA, "password");
        title = (TextView) findViewById(R.id.tv_information_details_title);
        icon = (ImageView) findViewById(R.id.iv_information_details_icon);
        content = (WebView) findViewById(R.id.tv_information_details_content);
        configWebview();
        search = (ImageView) findViewById(R.id.im_bar_top_conver_classify_search);
        share = (LinearLayout) findViewById(R.id.ll_information_default_share);
        comment = (LinearLayout) findViewById(R.id.ll_information_default_comment);
        feedLike = (LinearLayout) findViewById(R.id.ll_information_default_feedLike);

        collect = (CheckBox) findViewById(R.id.iv_information_details_collect);

        data = new InformationDetailsData();


        /**
         * 接收传递过来的位置进行显示详情
         */
        Intent intent = getIntent();
        positionId = intent.getIntExtra("position", 0);
        RequestParams params = new RequestParams();
        params.addBodyParameter("telphone", userTlephone);
        params.addBodyParameter("password", userPassword);
        params.addBodyParameter("id", positionId + "");
        getInformaitonDetails(params, HttpInterfaces.GetInfoDetails, Status.INIT);

        //判断是否收藏

        RequestParams paramsC = new RequestParams();
        paramsC.addBodyParameter("telphone", userTlephone);
        paramsC.addBodyParameter("password", userPassword);
        paramsC.addBodyParameter("id", positionId + "");
        paramsC.addBodyParameter("type", 4 + "");
        getInformaitonDetails(paramsC, HttpInterfaces.IfFavorite, Status.COLLECT_whether);

    }

    /**
     * 设置点击事件
     */
    private void setOnClickListener() {
        search.setOnClickListener(onClickListener);
        share.setOnClickListener(onClickListener);
        comment.setOnClickListener(onClickListener);
        feedLike.setOnClickListener(onClickListener);
        collect.setOnClickListener(onClickListener);

        //查看评论
        ((TextView) findViewById(R.id.tv_information_details_commentList)).setOnClickListener(onClickListener);


        /**
         * 分享的回调
         */
        oks.setCallback(new PlatformActionListener() {

            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
                RequestParams params = new RequestParams();
                params.addBodyParameter("telphone", userTlephone);
                params.addBodyParameter("password", userPassword);
                params.addBodyParameter("feed_id", data.getId() + "");
                getInformaitonDetails(params, HttpInterfaces.Feed_Share, Status.SHARE);
            }

            @Override
            public void onCancel(Platform arg0, int arg1) {
                // TODO Auto-generated method stub

            }
        });

    }

    /**
     * 处理监听
     */

    private OnClickListener onClickListener = new OnClickListener() {
        Intent intent = new Intent();

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.im_bar_top_conver_classify_search:
                    intent.setClass(InformationDetailsActivity.this, DynamicSearchActivity.class);
                    startActivity(intent);
                    break;
                // 分享
                case R.id.ll_information_default_share:
//                    SharedUtil.shered(InformationDetailsActivity.this, data.getUser_name(), "信息", "http://www.baidu.com", SystemTools.getHttpFileUrl(data.getImg_url()));

                    break;
                // 评论
                case R.id.ll_information_default_comment:
                    intent.setClass(InformationDetailsActivity.this, DynamicCommentActivity.class);
                    startActivityForResult(intent, 801);

                    break;
                // 赞
                case R.id.ll_information_default_feedLike:

                    RequestParams params2 = new RequestParams();
                    params2.addBodyParameter("telphone", userTlephone);
                    params2.addBodyParameter("password", userPassword);
                    params2.addBodyParameter("id", positionId + "");
                    params2.addBodyParameter("type", 4 + "");

                    getInformaitonDetails(params2, HttpInterfaces.Like_Add, Status.FEEDLIKE);

                    break;

                //收藏
                case R.id.iv_information_details_collect:

                    if (!collect.isSelected()) {
                        RequestParams params = new RequestParams();
                        params.addBodyParameter("telphone", userTlephone);
                        params.addBodyParameter("password", userPassword);
                        params.addBodyParameter("id", positionId + "");
                        params.addBodyParameter("type", 4 + "");

                        getInformaitonDetails(params, HttpInterfaces.Favorite_Add, Status.COLLECT);
                    } else {
                        RequestParams params = new RequestParams();
                        params.addBodyParameter("telphone", userTlephone);
                        params.addBodyParameter("password", userPassword);
                        params.addBodyParameter("id", positionId + "");
                        params.addBodyParameter("type", 4 + "");
                        getInformaitonDetails(params, HttpInterfaces.Favorite_Cancel, Status.COLLECT_cancel);
                    }


                    break;
                case R.id.tv_information_details_commentList:
                    intent.setClass(InformationDetailsActivity.this, InformationCommentActivity.class);
                    intent.putExtra("id", positionId);
                    startActivity(intent);
                    break;


                default:
                    break;
            }
        }
    };

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        /**
         * 接收评论内容
         */
        if (requestCode == 801 && resultCode == RESULT_OK) {

            RequestParams params = new RequestParams();
            params.addBodyParameter("telphone", userTlephone);
            params.addBodyParameter("password", userPassword);
            params.addBodyParameter("id", this.data.getId() + "");
            params.addBodyParameter("text", data.getStringExtra("commentText"));

            getInformaitonDetails(params, HttpInterfaces.InfoCommentAdd, Status.COMMENT);

        }
    }



    @SuppressLint("ResourceAsColor")
    @Override
    protected void onResume() {
        setTitleMore(View.VISIBLE, View.VISIBLE, "经营必看", null, null, null);
        setBackArrows(findViewById(R.id.bar_top_conver_classify_back));

        super.onResume();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    /**
     * 得到信息列表
     *
     * @param params
     * @param url
     * @param status
     */
    private void getInformaitonDetails(RequestParams params, String url, final Status status) {

        httpUtils.send(HttpMethod.POST, url, params, new MyRequestCallBack<String>(this, "页面加载中...") {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                super.onSuccess(responseInfo);

                try {

                    JSONObject json = new JSONObject(responseInfo.result);

                    //显示信息细节
                    if (status == Status.INIT) {
                        int result = json.getInt("Result");
                        if (result == 0) {
                            // 等于0为初始化调用
                            if (status == Status.INIT) {
                                JSONObject detail = json.getJSONObject("Details");
                                data = JsonHelper.parseObject(detail, InformationDetailsData.class);
                                // 设置标题
                                title.setText((detail.getString("title")));
                                content.loadUrl(HttpInterfaces.WEB_POST + "id=" + positionId);
                                // 设置图片
                                bitmapUtils.configDefaultLoadFailedImage(R.drawable.default_1);
                                bitmapUtils.display(icon, SystemTools.getHttpFileUrl(data.getImg_url()));


                                ((TextView) share.getChildAt(1)).setText(String.valueOf(data.getSharecount()));
                                ((TextView) comment.getChildAt(1)).setText(String.valueOf(data.getCommentcount()));
                                ((TextView) feedLike.getChildAt(1)).setText(String.valueOf(data.getLikecount()));

                            }
                        }
                    }

                    //点赞
                    if (status == Status.FEEDLIKE) {
                        int result = json.getInt("Result");
                        if (result == 0) {
                            int s = Integer.parseInt(((TextView) feedLike.getChildAt(1)).getText().toString()) + 1;


                            ((TextView) feedLike.getChildAt(1)).setText(String.valueOf(data.getLikecount() + 1));

                        } else if (result == 1) {
                            MyToast.show(InformationDetailsActivity.this, "不可重复点赞", 1);
                        }
                    }


                    //判断是否收藏
                    if (status == Status.COLLECT_whether) {

                        boolean result = json.getBoolean("Result");
                        if (result) {
                            boolean IfFavorite = json.getBoolean("IfFavorite");
                            if (IfFavorite) {
                                collect.setSelected(true);
                                ((TextView) findViewById(R.id.tv_information_details_collect)).setText("已收藏");
                            } else {
                                collect.setSelected(false);
                                ((TextView) findViewById(R.id.tv_information_details_collect)).setText("收藏");
                            }

                        }
                    }


                    //收藏
                    if (status == Status.COLLECT) {
                        int result = json.getInt("Result");
                        if (result == 0) {

                            collect.setSelected(true);
                            ((TextView) findViewById(R.id.tv_information_details_collect)).setText("已收藏");

                        }
                    }

                    //取消收藏
                    if (status == Status.COLLECT_cancel) {
                        int result = json.getInt("Result");
                        String msg = json.getString("Msg");
                        if (result == 0) {
                            collect.setSelected(false);
                            ((TextView) findViewById(R.id.tv_information_details_collect)).setText("收藏");

                        } else {
                            MyToast.show(InformationDetailsActivity.this, msg, 1);
                        }
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });

    }


    /**
     * 重新设置webview 属性
     */

    @SuppressWarnings("unused")
    private void configWebview() {
        // 设置文本编码
        content.getSettings().setDefaultTextEncodingName("utf-8");
        // 可以缩放
        content.getSettings().setSupportZoom(true);
        content.getSettings().setJavaScriptEnabled(true);
        content.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
        content.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        // 开启 Application Caches 功能
        content.getSettings().setAppCacheEnabled(false);
        content.getSettings().setLoadWithOverviewMode(true);
        // webView.getSettings().setDefaultZoom(ZoomDensity.MEDIUM);// 默认缩放模式
        content.getSettings().setUseWideViewPort(false);
    }

    /**
     * 获取到服务器数据后开始跟新UI
     */
    private void upDateUI() {

        // 配置webview数据源
        data.setContent("<style type=\"text/css\">*{ line-height:30px;}*{ font-size:15px;}img{WIDTH:100% !important;HEIGHT:auto !important;}"
                + getFont()
                + "</style><base href=\""
                + HttpInterfaces.ORG
                + "\"/>"
                + "<body class=\"Likun\" style=\"padding-left:2%;padding-right:2%;\">" + data.getContent() + "</body>");
        // 设置webview 加载数据
        content.loadDataWithBaseURL(null, data.getContent(), "text/html", "utf-8", null);
        MyLog.e("loadDataWithBaseURL", data.getContent());
    }

    /**
     * 更新地址
     *
     * @return
     */
    private String getFont() {
        StringBuilder builder = new StringBuilder();
        // <body class="MsoNormal"> </body>
        builder.append(".Likun { font-family: fzlt;}");
        builder.append("@font-face {font-family:fzlt;");
        builder.append("src:url(file:///android_asset/fzlt.ttf);}");
        return builder.toString();
    }

}
